import React, { useState, useEffect } from 'react';
import { Container, Row, Col, Card, Badge, Table } from 'react-bootstrap';
import { useParams } from 'react-router-dom';
import axios from 'axios';
import { Typography, Space, Button, Modal, Form, Input, message } from 'antd';

const { Title, Text } = Typography;

const CourseDetail = () => {
  const { courseId } = useParams();
  const [course, setCourse] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [ratingModalVisible, setRatingModalVisible] = useState(false);
  const [form] = Form.useForm();

  const renderScore = (score) => {
    console.log('Rendering score:', score, typeof score);
    // 检查score是否为数字类型的值
    if (score === null || score === undefined || isNaN(score)) {
      return '暂无评分';
    }
    // 确保score是数字
    const numScore = Number(score);
    return `${numScore.toFixed(1)} / 10`;
  };

  useEffect(() => {
    fetchCourseDetail();
  }, [courseId]);

  const fetchCourseDetail = async () => {
    try {
      console.log('Fetching course details for:', courseId);
      const response = await axios.get(`${process.env.REACT_APP_API_URL}/courses/${courseId}`);
      console.log('API Response:', response.data);
      
      if (response.data.status === 'success') {
        const courseData = response.data.data;
        console.log('Course Data:', courseData);
        setCourse(courseData);
      } else {
        setError(response.data.message || '获取课程详情失败');
      }
    } catch (error) {
      console.error('Error fetching course details:', error);
      setError('获取课程详情失败');
    } finally {
      setLoading(false);
    }
  };

  if (loading) return <div>加载中...</div>;
  if (error) return <div>错误: {error}</div>;
  if (!course) return <div>课程不存在</div>;

  console.log('Rendering course:', course);

  const renderSchedule = () => {
    return course.课程安排?.map((time, index) => (
      <Badge key={index} bg="info" className="me-2 mb-2">
        周{time.星期} {time.开始节次}-{time.结束节次}节
      </Badge>
    )) || [];
  };

  return (
    <Container className="py-4">
      <Row>
        <Col>
          <Card>
            <Card.Body>
              <Card.Title className="h2 mb-4">{course.课程名称}</Card.Title>
              <Row className="mb-4">
                <Col md={6}>
                  <p><strong>课程编号：</strong>{course.原始课程编号}</p>
                  <p><strong>课程名称：</strong>{course.课程名称}</p>
                  <p><strong>学分：</strong>{course.学分}</p>
                  <p><strong>任课教师：</strong>{course.教师姓名}</p>
                </Col>
                <Col md={6}>
                  <div className="rating-section">
                    <p>
                      <strong>水课程度：</strong>
                      <span className="ms-2">{renderScore(course.水课程度)}</span>
                      <small className="text-muted ms-2">（分数越高表示课程越轻松）</small>
                      {course.评价数量 > 0 && (
                        <small className="text-muted d-block">基于 {course.评价数量} 条评价</small>
                      )}
                    </p>
                    <p>
                      <strong>得分高低：</strong>
                      <span className="ms-2">{renderScore(course.得分高低)}</span>
                      <small className="text-muted ms-2">（分数越高表示容易得高分）</small>
                    </p>
                  </div>
                </Col>
              </Row>

              <div className="mb-4">
                <h5>授课教师</h5>
                <Table striped bordered hover>
                  <thead>
                    <tr>
                      <th>教师姓名</th>
                      <th>教室</th>
                    </tr>
                  </thead>
                  <tbody>
                    {course.授课教师?.map((teacher, index) => (
                      <tr key={index}>
                        <td>{teacher.教师姓名}</td>
                        <td>{teacher.教室 || '待定'}</td>
                      </tr>
                    ))}
                  </tbody>
                </Table>
              </div>

              {course.课程评价 && course.课程评价.length > 0 && (
                <div className="mb-4">
                  <h5>课程评价</h5>
                  <Table striped bordered hover>
                    <thead>
                      <tr>
                        <th>教师</th>
                        <th>水课程度</th>
                        <th>得分高低</th>
                      </tr>
                    </thead>
                    <tbody>
                      {course.课程评价.map((rating, index) => (
                        <tr key={index}>
                          <td>{rating.教师姓名}</td>
                          <td>{renderScore(rating.水课程度)}</td>
                          <td>{renderScore(rating.得分高低)}</td>
                        </tr>
                      ))}
                    </tbody>
                  </Table>
                </div>
              )}

              <div className="mb-4">
                <h5>上课时间</h5>
                <div>{renderSchedule()}</div>
              </div>

              {course.课程描述 && (
                <div className="mb-4">
                  <h5>课程描述</h5>
                  <p>{course.课程描述}</p>
                </div>
              )}

              <Button 
                type="primary" 
                onClick={() => setRatingModalVisible(true)}
                style={{ marginTop: '16px' }}
              >
                评价课程
              </Button>
            </Card.Body>
          </Card>
        </Col>
      </Row>

      <Modal
        title="课程评价"
        visible={ratingModalVisible}
        onCancel={() => setRatingModalVisible(false)}
        footer={null}
      >
        <Form
          form={form}
          onFinish={values => {
            axios.post('http://localhost:5000/api/courses/ratings', {
              "课程编号": course.原始课程编号,
              "教师编号": course.教师编号,
              "得分高低（1到10）": values.得分高低,
              "水课程度（1到10）": values.水课程度
            })
              .then(response => {
                if (response.data.status === 'success') {
                  message.success('评价提交成功！');
                  setRatingModalVisible(false);
                  form.resetFields();
                  // 刷新课程数据
                  axios.get(`http://localhost:5000/api/courses/${courseId}`)
                    .then(response => {
                      if (response.data.status === 'success') {
                        setCourse(response.data.data);
                      }
                    });
                } else {
                  message.error(response.data.message || '评价提交失败');
                }
              })
              .catch(error => {
                console.error('提交评价失败:', error);
                message.error('评价提交失败');
              });
          }}
        >
          <div style={{ marginBottom: 24 }}>
            <Text strong>评价课程：</Text>
            <Text>{course.课程名称}</Text>
          </div>
          <Form.Item
            name="得分高低"
            label="得分高低 (1-10分)"
            rules={[{ required: true, message: '请输入得分高低' }]}
          >
            <Input type="number" min="1" max="10" step="0.1" />
          </Form.Item>
          <Form.Item
            name="水课程度"
            label="水课程度 (1-10分)"
            rules={[{ required: true, message: '请输入水课程度' }]}
          >
            <Input type="number" min="1" max="10" step="0.1" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              提交评价
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </Container>
  );
};

export default CourseDetail; 